#include "bresenham.hpp"

#include <cmath>

namespace sdl_engine::component::graphics {

Bresenham::Bresenham(const Point& p1, const Point& p2): p1_(p1), p2_(p2) {
    dx_ = 2 * abs(p1.x - p2.x);
    dy_ = 2 * abs(p1.y - p2.y);
    sx_ = p1.x < p2.x ? 1 : p1.x == p2.x ? 0 : -1;
    sy_ = p1.y < p2.y ? 1 : p1.y == p2.y ? 0 : -1;
    err_ = dx_ >= dy_ ? - dx_ / 2 : - dy_ / 2;
}

void Bresenham::Step() {
    if (!IsFinished()) {
        if (dx_ >= dy_) {
            p1_.x += sx_;
            err_ += dy_;
            if (err_ >= 0) {
                p1_.y += sy_;
                err_ -= dx_;
            }
        } else {
            p1_.y += sy_;
            err_ += dx_;
            if (err_ >= 0) {
                p1_.x += sx_;
                err_ -= dy_;
            }
        }
    }
}

}
